package com.fbms.config;


import com.fbms.config.Interceptor.LoginInterceptor;
import com.fbms.config.Interceptor.RefreshTokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 类描述：
 *
 * @ClassName MvcConfig
 * @Author HappyBoy
 * @Date 2022-11-20 15:28
 **/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /**
     * StringRedisTemplate
     */
    private final StringRedisTemplate redisTemplate;

    @Autowired
    public WebMvcConfig(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 添加拦截器
     * @param registry 注册
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 默认按添加顺序执行 如有order order小的先执行
        // token刷新拦截器
        registry.addInterceptor(new RefreshTokenInterceptor(redisTemplate))
                .order(0);
        // 登录拦截器 拦截器的url是不包含配置文件中context-path配置的
        registry.addInterceptor(new LoginInterceptor())
                .excludePathPatterns(
                        "/login",
                        "/users"
                ).order(1);
    }

    /**
     * 允许跨域请求
     * @param corsRegistry 注册器
     */
    public void addCorsMappings(CorsRegistry corsRegistry){
        corsRegistry.addMapping("/**")
                .allowCredentials(true)
                .allowedMethods("GET", "POST")
                .allowedHeaders("*")
                .maxAge(3600);
    }
}
